# -*- coding: utf-8 -*-
from utils.parse_excel import ParseExcel
from action.page_action import *
import traceback
from utils.log import Logger
import logging
from config.constants import *
import unittest
from openpyxl import load_workbook


class HelpAddDelete(unittest.TestCase):

    def setUp(self) -> None:
        self.log = Logger(__name__, cmd_level=logging.INFO, file_level=logging.INFO)
        self.excelPath = projectPath + r'\testData\help_add_delete.xlsx'
        self.p = ParseExcel()
        self.wb = load_workbook(self.excelPath)
        self.sheet_name = self.wb.sheetnames  # 获取到excel的所有sheet名称

    def tearDown(self) -> None:
        self.wb.close()
        quit_browser()


    def test_help(self):
        try:
            test_case_pass_num = 0

            required_case = 0
            # 获取是否执行
            is_execute_column_values = self.p.get_column_value(self.excelPath, self.sheet_name[0], testCase_testIsExecute)
            # print(is_execute_column_values)
            for index, value in enumerate(is_execute_column_values):
                # 获取对应的步骤sheet名称
                step_sheet_name = self.p.get_cell_of_value(self.excelPath, self.sheet_name[0], index + 2, testCase_testStepName)
                # print(step_sheet_name)
                try:
                    if value and value.strip().lower() == 'y':
                        required_case += 1
                        test_step_pass_num = 0
                        # print('开始执行测试用例"{}"'.format(step_sheet_name))
                        self.log.logger.info(
                            '===============开始执行测试用例"{}"==============='.format(step_sheet_name))
                        # 如果用例被标记为执行y，切换到对应的sheet页
                        # 获取对应的sheet表中的总步骤数，关键字，定位方式，定位表达式，操作值
                        # 步骤总数
                        values = self.p.get_column_value(self.excelPath, step_sheet_name, testStep_testNum)
                        step_num = len(values)
                        # print(step_num)
                        self.log.logger.info('步骤总数："{}"'.format(step_num))
                        for step in range(2, step_num + 2):
                            raw_value = self.p.get_row_value(self.excelPath, step_sheet_name, step)
                            # 执行步骤名称
                            step_name = raw_value[testStep_testStepDescribe - 2]
                            # 关键字
                            key_word = raw_value[testStep_keyWord - 2]
                            # 定位方式
                            by = raw_value[testStep_elementBy - 2]
                            # 定位表达式
                            locator = raw_value[testStep_elementLocator - 2]
                            # 操作值
                            operate_value = raw_value[testStep_operateValue - 2]

                            if key_word and by and locator and operate_value:
                                func = key_word + '(' + '"' + by + '"' + ',' + '"' + locator + '"' + ',' + '"' + str(
                                    operate_value) + '"' + ')'
                                '''
                                input_value("xpath","","")
                                '''
                            elif key_word and by and locator and operate_value is None:
                                func = key_word + '(' + '"' + by + '"' + ',' + '"' + locator + '"' + ')'
                            elif key_word and operate_value and type(
                                    operate_value) == str and by is None and locator is None:
                                func = key_word + '(' + '"' + str(operate_value) + '"' + ')'
                            elif key_word and operate_value and type(
                                    operate_value) == int and by is None and locator is None:
                                func = key_word + '(' + str(operate_value) + ')'
                            else:
                                func = key_word + '(' + ')'

                            try:
                                # 执行测试步骤
                                eval(func)  # 将字符串转化为相应的对象
                            except Exception:
                                # 截图
                                pic_path = save_screen_shot()
                                # 写回测结果
                                error_info = traceback.format_exc()
                                self.p.write_test_result(self.excelPath, step_sheet_name, step, 'Failed', error_info, pic_path)
                                # print('步骤"{}"执行失败'.format(step_name))
                                self.log.logger.info('步骤"{}"执行失败'.format(step_name))
                                self.p.write_cell(self.excelPath, self.sheet_name[0], index + 2, testCase_testResult, 'Failed')
                                raise
                            else:
                                # print('步骤"{}"执行通过'.format(step_name))
                                self.log.logger.info('步骤"{}"执行通过'.format(step_name))
                                # 标记测试步骤为pass
                                self.p.write_test_result(self.excelPath, step_sheet_name, step, 'Pass')
                                test_step_pass_num += 1
                        # print(f'通过用例步骤数:{test_step_pass_num}')
                        self.log.logger.info(f'通过用例步骤数:{test_step_pass_num}')
                        if test_step_pass_num == step_num:
                            # 标记测试用例sheet页的执行结果为pass
                            self.p.write_cell(self.excelPath, self.sheet_name[0], index + 2, testCase_testResult, 'Pass')
                            test_case_pass_num += 1
                        # else:
                        #     self.p.write_cell(self.sheet_name[0], index + 2, testCase_testResult, 'Failed')
                        ParseExcel.write_current_time(self.excelPath, self.sheet_name[0], index + 2, testCase_testResult - 1)
                except Exception:
                    self.log.logger.info(f'===============用例"{step_sheet_name}"执行失败===============')
                    continue
            # print('共{}条用例，{}条需要被执行，本次执行通过{}条'.format(len(is_execute_column_values), required_case, test_case_pass_num))
            self.log.logger.info(
                '共{}条用例，{}条需要被执行，本次执行通过{}条'.format(len(is_execute_column_values), required_case,
                                                                    test_case_pass_num))
        except Exception as e:
            # print(traceback.format_exc(e))
            self.log.logger.info(traceback.format_exc())
            raise e


if __name__ == '__main__':
    # data = ["第1", "第2", "第3", "第4", "第5", "第6", "第7", "第8", "第9"]
    #
    # for index, value in enumerate(data, 0):
    #     print(f"index:{index},value:{value}")
    #
    # is_execute_column_values = p.get_column_value(sheet_name[0], testCase_testIsExecute)
    # print(is_execute_column_values)
    HelpAddDelete().test_help()

    eval('str("234")')

